package org.deltaset.faces.upload;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MultipartRequestWrapper extends HttpServletRequestWrapper {

    private final Map<String, List<String>> formParameterMap;
    private static final Logger logger = Logger.getLogger(MultipartRequestWrapper.class.getName());

    public MultipartRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        logger.log(Level.INFO, "!!!!!!!!! MultipartRequestWrapper constructor");
        final RequestParser requestParser = RequestParser.parse(request);
        formParameterMap = requestParser.getFormParameterMap();
        final FileRequest fileRequest = new FileRequest(requestParser.getFileParameterMap());
        FileRequestHolder.setFileRequest(fileRequest);
    }

    @Override
    public String getParameter(String name) {
        if (formParameterMap.containsKey(name)) {
            final List<String> values = formParameterMap.get(name);
            if (values.isEmpty()) {
                return "";
            } else {
                return values.get(0);
            }
        } else {
            return null;
        }
    }

    @Override
    public Map<String, List<String>> getParameterMap() {
        return Collections.unmodifiableMap(formParameterMap);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(formParameterMap.keySet());
    }

    @Override
    public String[] getParameterValues(String name) {
        if (formParameterMap.containsKey(name)) {
            final List<String> values = formParameterMap.get(name);
            if (values.isEmpty()) {
                return new String[0];
            } else {
                return values.toArray(new String[values.size()]);
            }
        } else {
            return null;
        }
    }
}
